import React, { useState, useEffect } from 'react'
import Loading from '@/components/Loading'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'

import { getIpLocationByNum } from '@/apis/file'
import { Button } from '@/components/ui/button'
import { MarkdownReader } from '@/components/ui/markdown-reader'

interface IpProps {
  ip: number
}

export function IpViewer({ ip }: IpProps) {
  const [location, setLocation] = useState<string | null>(null)
  const [loading, setLoading] = useState<boolean>(false)
  const [open, setOpen] = useState<boolean>(false)

  useEffect(() => {
    if (open && ip) {
      setLoading(true)
      getIpLocationByNum(ip)
        .then((location) => {
          if (location !== undefined) {
            setLocation(location)
          }
        })
        .finally(() => {
          setLoading(false)
        })
    }
  }, [open, ip])

  return (
    <div>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
          <Button
            variant="link"
            size="sm"
            className="h-auto p-0 text-xs text-gray-600 hover:text-gray-800 hover:underline"
          >
            查看IP
          </Button>
        </DialogTrigger>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>IP Location</DialogTitle>
          </DialogHeader>
          <DialogDescription>
            {loading ? (
              <Loading />
            ) : (
              <MarkdownReader content={location || ''} />
            )}
          </DialogDescription>
        </DialogContent>
      </Dialog>
    </div>
  )
}
